import { delCartApi, getCartListApi, insertCartApi } from '@/api/cart'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  //state 购物车数据
  const cartList = ref([])

  //获取最新购物车列表
  const updateCartList = async () => {
    const res = await getCartListApi()
    cartList.value = res.result
  }

  //action 定义添加购物车功能
  const addCart = async (good) => {
    const { skuId, count } = good
    if (isLogin.value) {
      //登录调用添加
      await insertCartApi({ skuId, count })
      //更新列表数据
      updateCartList()
    } else {
      //本地添加
      // 已添加过，count+1
      // 思路：通过匹配传过来的商品对象中的skuId能不能在cartList中找到
      const item = cartList.value.find((item) => item.skuId === good.skuId)
      if (item) {
        //找到了，原基础上+1
        item.count += 1
      } else {
        // 没有添加过商品，则push到购物车
        cartList.value.push(good)
      }
    }
  }

  //actions 定义删除购物车功能
  const delCart = async (skuId) => {
    if (isLogin.value) {
      //登录调用接口删除
      await delCartApi([skuId])
      //更新列表数据
      updateCartList()
    } else {
      //本地删除
      //根据skuId来删除对应的数组对象
      //思路1：找到元素下标，使用splice方法
      const idx = cartList.value.findIndex((item) => item.skuId === skuId)
      cartList.value.splice(idx, 1)
      //思路2：使用filter过滤
      // cartList.value=cartList.value.filter((item)=>item.skuId!==skuId)
    }
  }

  //actions 定义清除购物车功能
  const clearCart = () => {
    cartList.value = []
  }

  //action 根据skuId修改商品是否选中
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }

  //action 全选反选功能
  const allCheck = (selected) => {
    //将所有商品的选中状态都设置为全选框状态
    cartList.value.forEach((item) => item.selected = selected)
  }

  //计算属性
  //1.购物车总价
  const allPrice = computed(() => {
    return cartList.value.reduce((sum, item) => sum + item.count * item.price, 0)
  })
  //2.购物车商品总数量
  const allCount = computed(() => {
    return cartList.value.reduce((sum, item) => sum + item.count, 0)
  })
  //3.是否全选
  const isAll = computed(() => {
    return cartList.value.every((item) => item.selected)
  })
  //4.已选择的商品数量
  const selectedCount = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((sum, item) => sum + item.count, 0)
  })
  //5.已选择的商品总价
  const selectedPrice = computed(() => {
    return cartList.value.filter((item) => item.selected).reduce((sum, item) => sum + item.count * item.price, 0)
  })

  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    isAll,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCart,
    updateCartList
  }
}, {
  persist: true
})